﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class BackgroundManager : MonoBehaviour {
	
	public float Speed = 1;
	public Transform prefab;
	public Transform FollowPoint;
	public int numberOfObjects = 2;
	
	private Vector3 nextPosition;
	private float nextTransform;
	private float prevPoitPosition;
	private Queue<Transform> objectQueue;
	
	
	// Use this for initialization
	void Start () {
		objectQueue = new Queue<Transform>(numberOfObjects);
		objectQueue.Enqueue(prefab);
		nextPosition = prefab.localPosition;
		nextPosition.x += prefab.renderer.bounds.size.x;
		for (int i = 1; i < numberOfObjects; i++) {
			Transform o = (Transform)Instantiate(prefab);
			o.localPosition = nextPosition;
			nextPosition.x += prefab.renderer.bounds.size.x;
			objectQueue.Enqueue(o);
		}
		prevPoitPosition = prefab.localPosition.x;
		nextTransform = (nextPosition.x - prefab.position.x) / 2;
	}
	
	// Update is called once per frame
	void Update () {
		float pointPositioDifference = FollowPoint.position.x - prevPoitPosition;
		pointPositioDifference *= Speed;
		foreach (var item in objectQueue) 
			item.Translate(pointPositioDifference, 0, 0);
		nextTransform -= pointPositioDifference;
		nextPosition.x -= pointPositioDifference;
		prevPoitPosition = FollowPoint.position.x;

		if (FollowPoint.localPosition.x > nextTransform) {
			Transform o = objectQueue.Dequeue();
			o.localPosition = nextPosition;
			nextPosition.x += prefab.renderer.bounds.size.x;
			nextTransform += prefab.renderer.bounds.size.x;
			objectQueue.Enqueue(o);
		}
		
	}
}
